import { useRequest, useUnmount } from 'ahooks';
import { useHistory } from 'react-router-dom';
import {
  Form, Input, Button, message
} from 'antd';
import md5 from 'md5';
import * as APIS from '../../../../constants/api-constants';

export default () => {
  const history = useHistory();
  const [form] = Form.useForm();
  const { loading, run, cancel } = useRequest(
    (data) => {
      const { originalPassword, newPassword } = data;
      return {
        url: APIS.CHANGE_PASSWORD,
        method: 'PUT',
        data: {
          originalPassword: md5(originalPassword),
          newPassword: md5(newPassword),
        },
      };
    },
    {
      manual: true,
      onSuccess: (result) => {
        if (result.status === 200) {
          localStorage.removeItem('Authorization');
          history.push('/');
          message.success('密码修改成功');
        }
      },
      onError: () => {
        message.error('密码修改失败');
      },
    }
  );

  useUnmount(() => {
    cancel();
  });

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 8 },
  };
  return (
    <Form
      {...layout}
      form={form}
      onFinish={(data) => run(data)}
      validateTrigger="onBlur"
    >
      <Form.Item
        name="originalPassword"
        label="输入原始密码"
        rules={[
          {
            type: 'string',
            min: 6,
            max: 15,
            message: '密码需要大于6位并小于15位'
          },
          {
            required: true,
            message: '原始密码不能为空'
          }
        ]}
      >
        <Input placeholder="请输入原始密码" type="password" size="middle" />
      </Form.Item>
      <Form.Item
        name="newPassword"
        label="输入新密码"
        rules={[{
          type: 'string',
          min: 6,
          max: 15,
          message: '密码需要大于6位并小于15位'
        },
        {
          required: true,
          message: '新密码不能为空'
        }]}
      >
        <Input placeholder="请输入新密码" type="password" size="middle" />
      </Form.Item>
      <Form.Item
        name="confirmPassword"
        label="确认新密码"
        rules={[{
          type: 'string',
          min: 6,
          max: 15,
          message: '密码需要大于6位并小于15位'
        },
        {
          required: true,
          message: '确认密码不能为空'
        },
        ({ getFieldValue }) => ({
          validator(_, value) {
            if (!value || getFieldValue('newPassword') === value) {
              return Promise.resolve();
            }
            return Promise.reject(new Error('两次输入密码不一致!'));
          },
        }),
        ]}
      >
        <Input placeholder="请确认新密码" type="password" size="middle" />
      </Form.Item>
      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
        <Button
          loading={loading}
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          修改密码
        </Button>
      </Form.Item>
    </Form>
  );
};
